/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.openrdf.repository.sparql.SPARQLRepository;

import be.destin.util.RunCommand;
import be.destin.util.Util;

public class SparqlPool extends ConnectionPool {

	/** log4j category */
	private static Logger log = Logger.getLogger(SparqlPool.class);

	SPARQLRepository repository = null;

	public static SparqlPool getSparqlPool(String name) {
		return (SparqlPool) openedPools.get(name);
	}

	public static synchronized SparqlPool getSparqlConnection(String configFile, String name) {
	    name = name.trim();
		if (openedPools.containsKey(name)) {
			return (SparqlPool) openedPools.get(name);
		}
		String poolConfig = configFile;
		SparqlPool pool = null;
		FileInputStream is = null;
		try {
			// Open pool configuration file in subdirectory "pool"
			poolConfig = (new File(configFile)).getCanonicalFile().getParent()+File.separator
			+ name + "-pool.cfg";
			is = new FileInputStream(poolConfig);
			pool = new SparqlPool();
			pool.properties = new Properties();
			pool.properties.load(is);
		} catch ( FileNotFoundException e ) {
			log.error("Read SparQL connection configuration from pool "+name+" in "+poolConfig+": "+e.toString());
		} catch ( IOException e ) {
			log.error("Read SparQL connection configuration from pool "+name+" in "+poolConfig+": "+e.toString());
		}
		RunCommand.closeAble(is, "configuration for pool "+name+" in "+poolConfig);
		if (pool == null) return null;

		// Parameters for SPARQL accesses
		pool.validationQuery = pool.properties.getProperty("validation",
		"SELECT ?s ?o ?p WHERE {?s ?o ?p} LIMIT 1");

		pool.dbURL = pool.properties.getProperty("url"); // URL for
		// connecting to
		// database, e.g.
		// jdbc:postgresql://localhost:5432/dspace

		pool.dbUsername = pool.properties.getProperty("username");
		pool.dbPassword = pool.properties.getProperty("password");

		// Read pool configuration parameter or use defaults
		// Note we check to see if property is null; getIntProperty
		// returns
		// '0' if the property is not set OR if it is actually set to
		// zero.
		// But 0 is a valid option...
		pool.maxConnections = Util.string2int(pool.properties
				.getProperty("maxconnections"), 30);
		pool.maxWait = Util.string2int(pool.properties.getProperty("maxwait"),
				15000);
		pool.maxIdle = Util.string2int(pool.properties.getProperty("maxidle"), -1);

		pool.setName(name);
		pool.repository = new SPARQLRepository(pool.dbURL);
		return pool;
	}

	public Map<String,String> evalMap(String query) {
		return new HashMap<String,String>();
	}
/*
		if (query == null || query.length()==0) return null;

		Map<String,String> aMap = null;
		Connection con = getConnection();
		if (con != null) {
			log.debug(query);
			// create and execute a SELECT
			Statement stmt = null;
			ResultSet rs = null;
			try {
				stmt = con.createStatement();
				rs = stmt.executeQuery(query);

				aMap = new HashMap<String,String>();
				while (rs.next()) {
					String currCode = rs.getString("key");
					if (currCode == null || currCode.length() == 0) {
						log
						.error(query
								+ ": key field is not returned by SQL query");
						break;
					}
					String currValue = rs.getString("value");
					if (currValue == null) {
						log
						.error(query
								+ ": value field is not returned by SQL query");
						break;
					}
					aMap.put(currCode, currValue);
				}
			} catch (SQLException ex) {
				log.error(query + " : ", ex);
				Util.printStack(ex);
			}
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
				}
			}
			freeConnection(con);
		}
		return aMap;
	} */

	public String getUrl() {
		return dbURL;
	}

	public void setUrl(String dbURL) {
		this.dbURL = dbURL;
	}

	public String getUsername() {
		return dbUsername;
	}

	public void setUsername(String dbUsername) {
		this.dbUsername = dbUsername;
	}

	public String getPassword() {
		return dbPassword;
	}

	public void setPassword(String dbPassword) {
		this.dbPassword = dbPassword;
	}

	public String getValidationQuery() {
		return validationQuery;
	}

	public void setValidationQuery(String validationQuery) {
		this.validationQuery = validationQuery;
	}

	public int getMaxConnections() {
		return maxConnections;
	}

	public void setMaxConnections(int maxConnections) {
		this.maxConnections = maxConnections;
	}

	public int getMaxWait() {
		return maxWait;
	}

	public void setMaxWait(int maxWait) {
		this.maxWait = maxWait;
	}

	public int getMaxIdle() {
		return maxIdle;
	}

	public void setMaxIdle(int maxIdle) {
		this.maxIdle = maxIdle;
	}

	public SPARQLRepository getRepository() {
		return repository;
	}

	public void setRepository(SPARQLRepository repository) {
		this.repository = repository;
	}
}
